#include <iostream>
//P_xxx表示只允许在当前目录中包含,不允许进行跨目录操作.
#include <zlib/eventsystem/I_Event.h>
#include <zlib/eventsystem/I_Thread.h>

using namespace std;

class TestCont : public Continuation
{
public:
	TestCont()
	{
		cout << "construct function, set callback is mainHandler" << endl;
		SET_HANDLER(&TestCont::mainHandler);
	}

	~TestCont()
	{
		cout << "destory function" << endl;	
	}

	int mainHandler(int event, void *data)
	{
		cout << "test event" << endl;
	}
};


int main()
{
	EThread *et = new EThread(1);

	TestCont *t = new TestCont;
	t->mutex = new_ProxyMutex();

	Event *e = new Event;
	e->init(t, 0, 0);
	e->mutex = t->mutex;
	e->callback_event = EVENT_IMMDIATE;
	cout << "immediate:" << e->immediate << " timeout_at:" << e->timeout_at << " period:" << e->period << endl;

	
	MUTEX_TRY_LOCK(l, e->mutex, et);
	if(!l.is_locked())
	{
		cout << "try lock faild, exit" << endl;
		return 1;
	}

	if(!e->cancelled) {
		e->continuation->handleEvent(e->callback_event, e);
	}else{
		cout << "the event is cancled" << endl;
	}
	e->free();
	

	Event *e1 = new Event;
	e1->init(t, 1, 1);
	e1->mutex = t->mutex;
	e1->callback_event = EVENT_INTERVAL;
	cout << "immediate:" << e->immediate << " timeout_at:" << e->timeout_at << " period:" << e->period << endl;
	
	//可能是异步销毁continuation,所以在销毁continuation时需要持有它的锁
	//如果continuation先于event销毁.则需要取消异步任务.
	delete t;

	MUTEX_TRY_LOCK(l1, e1->mutex, et);
	if(!l1.is_locked())
	{
		cout << "try lock faild, exit" << endl;
		return 1;
	}

	e1->cancle_action();
	if(!e1->cancelled){
		e1->continuation->handleEvent(e->callback_event, e);
	}else{
		cout << "the event is cancled" << endl;
	}
	e1->free();

	return 0;
}

